// pages/createOrder/createOrder.js
const phoneNumber = wx.getStorageSync('userInfo').account
const name = wx.getStorageSync('userInfo').nickName
const db = wx.cloud.database()
const _ = db.command
import common from "../../utils/getcurrentTime.js"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    name,
    phoneNumber,
    address:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {selectedProducts,allPrice} = options
    this.setData({
      selectedProducts:JSON.parse(selectedProducts),
      allPrice,
    })
  },

  onShow(){
    db.collection('shoppingCart').where({
       account:phoneNumber
     }).get().then(res=>{
       this.setData({
         shoppingCartId:res.data[0]._id
        })
     }).catch(error=>{
       console.log(error)
     })
  },

  //获取当前位置
  chooseLocation(){
    wx.chooseLocation({
    }).then(res=>{
      this.setData({
        address:res.address
      })
    })
  },

  getName(e){
   this.setData({
     name:e.detail.value
   })
  },

  getphoneNumber(e){
    this.setData({
      phoneNumber:e.detail.value
    })
  },

  getaddress(e){
    this.setData({
      address:e.detail.value
    })
  },

  //提交订单
  createOrder(){
    let {name,phoneNumber,address,allPrice,selectedProducts} = this.data
    let account = wx.getStorageSync('userInfo').account

    if(name.length == 0){
      wx.showToast({
        title: '收货人未填写',
        icon:'error',
      })
      return
    }else if(phoneNumber.length == 0){
      wx.showToast({
        title: '电话未填写',
        icon:'error',
      })
      return
    }else if(address.length == 0){
      wx.showToast({
        title: '地址未填写',
        icon:'error',
      })
      return
    }

    wx.showModal({
      content:'您将支付'+allPrice+'元，确认支付？'
    }).then(res=>{
      if(res.cancel){
        //生成订单，但订单待付款
        this.uploadOrdersToCloud(name,phoneNumber,selectedProducts,allPrice,address,'待付款')
      }else if(res.confirm){
        //判断用户余额是否足够

        db.collection('userList').where({
          account,
        }).get().then(res=>{
          let balance = res.data[0].balance
          if(balance - allPrice < 0){
            //余额不足，生成订单，但订单待付款
            this.uploadOrdersToCloud(name,phoneNumber,selectedProducts,allPrice,address,'待付款')
            wx.showModal({
              content:'余额不足，是否充值？'
            }).then(res=>{
              if(res.confirm){
                wx.navigateTo({
                  url: '/pages/wallet/wallet',
                })
              }
            })
          }else{
            //余额够，生成订单，订单状态：待发货
            //从用户余额中扣除响应金额
            db.collection('userList').where({
              account,
            }).get().then(res=>{
              let {_id,balance} = res.data[0]
              balance = parseFloat((balance - parseFloat(allPrice)).toFixed(2))
              db.collection('userList').doc(_id).update({
                data:{
                  balance,
                }
              }).then(res=>{
                wx.showToast({
                  title: '支付成功',
                  icon:'success'
                })
                this.uploadOrdersToCloud(name,phoneNumber,selectedProducts,allPrice,address,'待配送').then(()=>{
                  wx.reLaunch({
                    url: '/pages/order/order',
                  })
                })

              }).catch(error=>{
                console.log(error)
                wx.showToast({
                  title: '支付失败',
                  icon:'error'
                })
              })
            })
          }
        }).catch(error=>{
          console.log(error)
        })
      }
    })
  },

   //生成订单
   uploadOrdersToCloud(name,account,selectedProducts,allPrice,address,state){ 
     for(let item of selectedProducts){
       console.log(item)
       console.log(this.data.shoppingCartId)
       db.collection('shoppingCart').doc(this.data.shoppingCartId).update({
         data:{
          products:_.pull({
            _id:item._id
          })
         }
       }).then(res=>{
          console.log(res)
       }).catch(error=>{
         console.log(error)
       })
     }
    return db.collection('orders').add({
              data:{
                name,
                account,
                products:selectedProducts,
                payment:allPrice,
                time:common.setDate(Date.now(),'Y-m-d H:i:s'),
                address,
                state,
              }
            })
  }
})